package com.xiaocai.myblog.common;

import com.xiaocai.myblog.enums.ErrorCodeEnum;
import com.xiaocai.myblog.enums.ResponseEnum;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author chenhefu
 * @date 2019-10-01 03:05
 */
@ControllerAdvice
public class ResponseHandler implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        ResponseData<Object> d = new ResponseData<>();
        if (body instanceof ErrorCodeEnum) {
            ErrorCodeEnum errorCode = (ErrorCodeEnum) body;
            d.setCode(errorCode.getCode());
            d.setMsg(errorCode.getMsg());
        } else if (!(body instanceof ResponseData) & !(body instanceof SuccessResponseData)) {
            d.setCode(ResponseEnum.SUCCESS.getCode());
            d.setMsg(ResponseEnum.SUCCESS.getMsg());
            d.setData(body);
        } else {
            return body;
        }
        return d;
    }
}
